package com.study.view;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.study.view.adapter.MRecyclerViewAdapter;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MRecyclerViewActivity extends AppCompatActivity {


    RecyclerView recyclerView;
    MRecyclerViewAdapter adapter;
    LinearLayout suspensionBar;
    ImageView iv_avatar;
    TextView nickName;

    //悬浮条的高度
    private int mSuspensionHeight;

    //初始化位置
    private int mCurrentPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        suspensionBar = findViewById(R.id.suspensionBar);
        iv_avatar = findViewById(R.id.iv_avatar);
        nickName = findViewById(R.id.nickName);

        recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        adapter = new MRecyclerViewAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.setHasFixedSize(true);


        //监听RecylerView 的滑动
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                //距离顶部的距离
                mSuspensionHeight = suspensionBar.getHeight();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //根据滚动的位置对悬浮条进行调整

                //根据后一个item的位置来判断上一个悬浮条的位置
                View view = layoutManager.findViewByPosition(mCurrentPosition+1);
                if(view!=null){

                    if(view.getTop() <= mSuspensionHeight){
                        //需要对悬浮条进行移动
                        suspensionBar.setY(-(mSuspensionHeight-view.getTop()));
                    }else{
                        //保持原来地方的位置
                        suspensionBar.setY(0);
                    }
                }

                if(mCurrentPosition != layoutManager.findFirstVisibleItemPosition()){
                    mCurrentPosition = layoutManager.findFirstVisibleItemPosition();
                    //更新悬浮条的信息
                    updateSuspension();
                }
            }
        });

        //初始化需要更新下悬浮条
        updateSuspension();
    }

    private void updateSuspension() {
        nickName.setText(mCurrentPosition+"Marry Js");
    }
}
